import { createRouter, createWebHistory } from 'vue-router'
import { authService } from '@/services/authService'
import HomeView from '../views/HomeView.vue'
import ProductDetailView from '../views/ProductDetailView.vue'
import LoginView from '../views/LoginView.vue'
import SecurityView from '../views/SecurityView.vue'

// 动态计算base路径
const getBasePath = () => {
  // 开发环境使用默认路径
  if (import.meta.env.DEV) {
    return import.meta.env.BASE_URL
  }
  
  // 生产环境动态检测路径
  const currentPath = window.location.pathname
  console.log('Router - Current path:', currentPath)
  
  // 如果在子系统下（如 /test/），返回子系统路径
  if (currentPath !== '/' && currentPath !== '') {
    const pathSegments = currentPath.split('/').filter(Boolean)
    console.log('Router - Path segments:', pathSegments)
    if (pathSegments.length > 0) {
      const basePath = `/${pathSegments[0]}/`
      console.log('Router - Base path:', basePath)
      return basePath
    }
  }
  
  console.log('Router - Using root base path: /')
  return '/'
}

const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        requiresAuth: false,
        hideWhenAuthenticated: true // 已登录时隐藏登录页
      }
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/product/:id',
      name: 'product-detail',
      component: ProductDetailView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/security',
      name: 'security',
      component: SecurityView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
      meta: {
        requiresAuth: true
      }
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = authService.isAuthenticated()
  
  // 如果路由需要认证但用户未登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 保存原始路径，登录后跳转回来
    next({
      name: 'login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 如果用户已登录但访问登录页，重定向到首页
  if (to.meta.hideWhenAuthenticated && isAuthenticated) {
    next({ name: 'home' })
    return
  }
  
  next()
})

export default router
